<!DOCTYPE html>
<html lang="${LANG}" class="dark">

<head>
    <meta charset="UTF-8">
    <title>QBT_TR(Speed limit)QBT_TR[CONTEXT=SpeedLimit]</title>
    <link rel="stylesheet" href="css/style.css?v=${CACHEID}" type="text/css">
    <script defer src="scripts/localpreferences.js?v=${CACHEID}"></script>
    <script defer src="scripts/color-scheme.js?v=${CACHEID}"></script>
    <script>
        "use strict";

        window.addEventListener("DOMContentLoaded", (event) => {
            const applyButton = document.getElementById("applyButton");

            window.addEventListener("keydown", (event) => {
                switch (event.key) {
                    case "Enter":
                        event.preventDefault();
                        applyButton.click();
                        break;
                    case "Escape":
                        event.preventDefault();
                        window.parent.qBittorrent.Client.closeFrameWindow(window);
                        break;
                }
            });

            const params = new URLSearchParams(window.location.search);
            const type = params.get("type");
            const hashes = params.get("hashes").split("|");

            const isGlobal = (hashes[0] === "global");
            // Otherwise it's download limit
            const isUpload = (type === "upload");

            const getLimitMethod = isUpload ? "uploadLimit" : "downloadLimit";
            const setLimitMethod = isUpload ? "setUploadLimit" : "setDownloadLimit";

            const limitUpdateValue = document.getElementById("limitUpdateValue");
            const limitUnit = document.getElementById("limitUnit");

            const setLimitUpdateValue = (value) => {
                if (value === 0) {
                    limitUpdateValue.value = "∞";
                    limitUnit.style.visibility = "hidden";
                }
                else {
                    limitUpdateValue.value = value;
                    limitUnit.style.visibility = "visible";
                }
            };

            const setupSlider = (limit, maximum) => {
                const input = document.getElementById("limitSliderInput");
                input.max = maximum;
                input.value = limit;
                input.addEventListener("input", (event) => {
                    setLimitUpdateValue(Number(event.target.value));
                });
                // Set default value
                setLimitUpdateValue(limit);
            };

            applyButton.addEventListener("click", (event) => {
                const limit = Number(limitUpdateValue.value) * 1024;
                if (isGlobal) {
                    fetch(`api/v2/transfer/${setLimitMethod}`, {
                            method: "POST",
                            body: new URLSearchParams({
                                limit: limit
                            })
                        })
                        .then((response) => {
                            if (!response.ok)
                                return;

                            window.parent.updateMainData();
                            window.parent.qBittorrent.Client.closeFrameWindow(window);
                        });
                }
                else {
                    fetch(`api/v2/torrents/${setLimitMethod}`, {
                            method: "POST",
                            body: new URLSearchParams({
                                hashes: hashes.join("|"),
                                limit: limit
                            })
                        })
                        .then((response) => {
                            if (!response.ok)
                                return;

                            window.parent.qBittorrent.Client.closeFrameWindow(window);
                        });
                }
            });

            document.getElementById("limitUpdateLabel").textContent =
                isUpload
                ? "QBT_TR(Upload limit:)QBT_TR[CONTEXT=SpeedLimit]"
                : "QBT_TR(Download limit:)QBT_TR[CONTEXT=SpeedLimit]";

            fetch(`api/v2/transfer/${getLimitMethod}`, {
                    method: "GET",
                    cache: "no-store"
                })
                .then(async (response) => {
                    if (!response.ok)
                        return;

                    const data = await response.text();

                    const globalLimit = Math.max((Number(data) / 1024), 0);

                    // Get torrents download limit
                    // And create slider
                    if (isGlobal) {
                        setupSlider(globalLimit, 10000);
                    }
                    else {
                        fetch(`api/v2/torrents/${getLimitMethod}`, {
                                method: "POST",
                                body: new URLSearchParams({
                                    hashes: hashes.join("|")
                                })
                            })
                            .then(async (response) => {
                                if (!response.ok)
                                    return;

                                const data = await response.json();

                                const firstLimit = Math.max(data[hashes[0]], 0);
                                const isAllFirstLimit = Object.values(data).every(value => value === firstLimit);
                                const limit = isAllFirstLimit ? Math.round(firstLimit / 1024) : 0;

                                setupSlider(limit, ((globalLimit > 0) ? globalLimit : 1000));
                            });
                    }
                });

            limitUpdateValue.focus();
        });
    </script>
</head>

<body>
    <div style="padding-top: 10px; width: 100%; text-align: center; margin: 0 auto; overflow: hidden">
        <div class="slider">
            <div class="update">
                <label id="limitUpdateLabel" for="limitUpdateValue">QBT_TR(Limit:)QBT_TR[CONTEXT=SpeedLimit]</label>
                <input type="text" id="limitUpdateValue" size="6" placeholder="∞" style="text-align: center;">
                <span id="limitUnit">QBT_TR(KiB/s)QBT_TR[CONTEXT=SpeedLimit]</span>
            </div>
            <input type="range" id="limitSliderInput" min="0" value="0" style="width: 100%;" aria-label="QBT_TR(Speed limit)QBT_TR[CONTEXT=SpeedLimit]">
        </div>
        <input type="button" id="applyButton" value="QBT_TR(Apply)QBT_TR[CONTEXT=HttpServer]">
    </div>
</body>

</html>
